package com.zhengqiangblog.blog.web;

import java.util.List;

import org.apache.log4j.Logger;

import com.zhengqiangblog.blog.model.Article;
import com.zhengqiangblog.blog.model.Pagination;
import com.zhengqiangblog.blog.service.ArticleService;
import com.zhengqiangblog.blog.service.PaginationCalculator;
import com.zhengqiangblog.blog.service.SideBarService;
import com.zhengqiangblog.blog.web.form.PageForm;
import com.zhengqiangblog.core.ApplicationContext;
import com.zhengqiangblog.core.Model;
import com.zhengqiangblog.core.Result;

public class IndexAction {

	private static final Logger logger = Logger.getLogger(IndexAction.class);

	private ArticleService articleService = ApplicationContext.get(ArticleService.class);
	private PaginationCalculator paginationCalculator = ApplicationContext.get(PaginationCalculator.class);
	private SideBarService sideBarService = ApplicationContext.get(SideBarService.class);

	public IndexAction() {
		logger.info("IndexAction initializing...");
	}

	public String execute(Model model, PageForm form) throws Exception {
		int totalItems = articleService.getArticleIdList().size();
		Pagination pagination = paginationCalculator.calculate(form.getPage(), totalItems);
		model.addAttribute("pagination", pagination);
		int start = (pagination.getPageNo() - 1) * pagination.getPageSize();
		List<Article> articles = articleService.getArticleList(start, pagination.getPageSize());
		model.addAttribute("articles", articles);
		sideBarService.initialize(model);
		return Result.HOME;
	}

}
